package com.fqxiny.lease.web.admin.service.impl;

import com.fqxiny.lease.common.minio.MinioConfiguration;
import com.fqxiny.lease.common.minio.MinioProperties;
import com.fqxiny.lease.web.admin.service.FileService;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import io.minio.*;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


/**
 * @author : 戚欣扬
 * @code :
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;
    @Autowired
    MinioConfiguration minioConfiguration;

    @Override
    public String upload(MultipartFile file) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String bucketName = minioProperties.getBucketName();
        boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        //3.不存在创建桶，修改权限
        if (!bucketExists){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            //设置hello-minio桶的访问权限
            String policy = """
                        {
                          "Statement" : [ {
                            "Action" : "s3:GetObject",
                            "Effect" : "Allow",
                            "Principal" : "*",
                            "Resource" : "arn:aws:s3:::lease/*"
                          } ],
                          "Version" : "2012-10-17"
                        }""";
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(policy).build());
        }
        // 4. 上传对象
        //避免名称重复，避免覆盖 ； 在桶中创建一个文件夹 / 文件名
        String filename = new SimpleDateFormat("yyyyMMdd").format(new Date()) +
                "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();


        minioClient.putObject(PutObjectArgs.builder()
                        .bucket(bucketName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .object(filename)
                        .contentType(file.getContentType())
                        .build());

        return String.join("/",minioProperties.getEndpoint(),minioProperties.getBucketName(),filename);
    }

}


